package com.bw.educate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.educate.common.ResponseResult;
import com.bw.educate.entity.EduCourseBase;
import com.bw.educate.entity.EduTeacher;
import com.bw.educate.mapper.EduTeacherMapper;
import com.bw.educate.service.IEduTeacherService;
import com.bw.educate.teacherClient.TeacherClient;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@Service
public class EduTeacherServiceImpl extends ServiceImpl<EduTeacherMapper, EduTeacher> implements IEduTeacherService {

    @Autowired
    private EduTeacherMapper teacherMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TeacherClient teacherClient;

    @Value("${htmlPath}")
    private String htmlPath;

    /**
     * 课程下拉框展示讲师列表
     **/
    @Override
    public ResponseResult teacherList() {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            List list = teacherMapper.selectList(queryWrapper);
            result.setResult(list);
            result.setMessage("查询成功！！！");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败！！！"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 讲师C端页面展示
     **/
    @Override
    public ResponseResult teacherShowList() {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            List<EduTeacher> teacherList=redisTemplate.opsForHash().values("teacherList");//缓存中获取讲师信息的集合
            result.setResult(teacherList);
            if(teacherList==null||teacherList.size()<=0){//缓存中无商品数据
                QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper();
                queryWrapper.lambda().orderByDesc(EduTeacher::getSort).eq(EduTeacher::getIsDelete,"0");//按照排序进行倒叙排序
                List<EduTeacher> list=teacherMapper.selectList(queryWrapper);
                for (EduTeacher teacher:list) {
                    redisTemplate.opsForHash().put("teacherList",String.valueOf(teacher.getId()),teacher);
                }
                result.setResult(list);
            }
            result.setMessage("查询成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询失败" + e.toString());
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 将添加好的讲师生成静态页
     **/
    @Override
    public ResponseResult generatePage(Long id) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            //添加的同时生成静态的详情页面，放到服务器的目录下
            EduTeacher byId = teacherMapper.selectById(id);
            getHtlm(byId);
            result.setMessage("生成成功");
            byId.setGenerate(1);
            teacherMapper.updateById(byId);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("生成失败"+e.toString());
        }

        return result;
    }

    /**
     * 删除生成的静态页面
     **/
    @Override
    public ResponseResult delPage(Long id) {
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            EduTeacher byId = teacherMapper.selectById(id);
            //删除已生成静态的详情页面
            File file = new File(htmlPath+byId.getId()+".html");
            file.delete();
            result.setMessage("删除成功");
            byId.setGenerate(0);
            teacherMapper.updateById(byId);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("删除失败"+e.toString());
        }

        return result;
    }

    public void getHtlm(EduTeacher eduTeacher){
        try {
            //创建模板引擎配置类
            Configuration configuration = new Configuration(Configuration.getVersion());
            ClassPathResource classPathResource = new ClassPathResource("template");
            //加载模板的路径【文件目录或文件夹】
            configuration.setDirectoryForTemplateLoading(classPathResource.getFile());
            //设置编码格式
            configuration.setDefaultEncoding("utf-8");
            //获取具体的模板文件
            Template template = configuration.getTemplate("teacher.html");

            //通过服务调用，根据讲师id查询课程信息
            List<EduCourseBase> byTeacherId = teacherClient.getByTeacherId(eduTeacher.getId());

            //定义数据
            Map map = new HashMap();
            map.put("teacher", JSON.toJSONString(eduTeacher));
            map.put("course", JSON.toJSONString(byTeacherId));

            //模板+数据=页面

            String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            //将字符串换成输入流
            InputStream inputStream = IOUtils.toInputStream(htmlStr, "utf-8");
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlPath+eduTeacher.getId()+".html");
            IOUtils.copy(inputStream,outputStream);
            inputStream.close();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
